package com.imdroid.carac.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.model.User;
import com.imdroid.carac.process.ProcessFactory;
import com.imdroid.carac.process.UserProcess;

/**
 * The startup activity
 * 
 */
public class StartupActivity extends BaseActivity implements OnClickListener {
	/**
	 * The regiser button
	 */
	private Button buttonRegister;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.startup);
		buttonRegister = (Button) this.findViewById(R.id.my_btn_register);
		buttonRegister.setOnClickListener(this);

		// 判断是否注册车机器
		if (IMDroid.hasRegister()) {
			Intent intent = new Intent();
			intent.setClass(StartupActivity.this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			this.finish();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View view) {
		if (view.getId() == buttonRegister.getId()) {
			ProgressDialogHelper.showProgress(this, "请稍候",
					getString(R.string.text_loading));
			new Thread() {
				public void run() {
					try {
						String IMEI = IMDroid.getDeviceIMEI();
						String SIM = IMDroid.getDeviceSIM();
						UserProcess process = (UserProcess) ProcessFactory
								.getProcess(UserProcess.class);
						User user = process.getUser(IMEI, SIM);
						IMDroid.registerUser(user);

						StartupActivity.this.sendMessage(MESSAGE_FINISH);
					} catch (Exception ex) {
						ex.printStackTrace();
						StartupActivity.this.sendMessage(MESSAGE_ERROR,
								ex.getClass() + " " + ex.getMessage());
					}
				}
			}.start();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.imdroid.carac.activities.BaseActivity#processedMessage(android.os
	 * .Message)
	 */
	public void processedMessage(Message msg) {
		switch (msg.what) {
		case MESSAGE_FINISH:
			// 转移到第一个注册页面
			Intent intent = new Intent();
			intent.setClass(StartupActivity.this, Register1Activity.class);
			startActivity(intent);
			ProgressDialogHelper.dismissProgress();
			this.finish();
			break;
		case MESSAGE_ERROR:
			showAlert((String) msg.obj);
			ProgressDialogHelper.dismissProgress();
			break;
		}
	}
}